package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.PUserBill;
import com.ruoyi.system.domain.bo.POrderBo;
import com.ruoyi.system.domain.bo.PUserBillBo;
import com.ruoyi.system.domain.bo.UserRechargeRequest;
import com.ruoyi.system.domain.vo.PUserBillVo;
import com.ruoyi.system.domain.vo.WalletVO;
import com.ruoyi.system.mapper.PUserBillMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.IPUserBillService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 账单Service业务层处理
 *
 * @author ruoyi
 * @date 2022-07-26
 */
@RequiredArgsConstructor
@Service
public class PUserBillServiceImpl implements IPUserBillService {

    private final PUserBillMapper baseMapper;
    private final SysUserMapper userMapper;

    /**
     * 查询账单
     */
    @Override
    public PUserBillVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询账单列表
     */
    @Override
    public TableDataInfo<PUserBillVo> queryPageList(PUserBillBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<PUserBill> lqw = buildQueryWrapper(bo);
        Page<PUserBillVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询账单列表
     */
    @Override
    public List<PUserBillVo> queryList(PUserBillBo bo) {
        LambdaQueryWrapper<PUserBill> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<PUserBill> buildQueryWrapper(PUserBillBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<PUserBill> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getUserId() != null, PUserBill::getUserId, bo.getUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getTitle()), PUserBill::getTitle, bo.getTitle());
        lqw.eq(StringUtils.isNotBlank(bo.getCategory()), PUserBill::getCategory, bo.getCategory());
        lqw.eq(StringUtils.isNotBlank(bo.getPayType()), PUserBill::getPayType, bo.getPayType());
        lqw.eq(StringUtils.isNotBlank(bo.getType()), PUserBill::getType, bo.getType());
        lqw.eq(bo.getNumber() != null, PUserBill::getNumber, bo.getNumber());
        return lqw;
    }

    /**
     * 新增账单
     */
    @Override
    public Boolean insertByBo(PUserBillBo bo) {
        PUserBill add = BeanUtil.toBean(bo, PUserBill.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改账单
     */
    @Override
    public Boolean updateByBo(PUserBillBo bo) {
        PUserBill update = BeanUtil.toBean(bo, PUserBill.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(PUserBill entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除账单
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public void chargeMoney(UserRechargeRequest rechargeRequest) {
        if (ObjectUtil.isEmpty(rechargeRequest)) {
            throw new ServiceException("非法参数！");
        }

        BigDecimal price = rechargeRequest.getPrice();
        if (price.compareTo(BigDecimal.ZERO) <= 0) {
            throw new ServiceException("非法金额！");
        }
        // 设置金额
        Long userId = LoginHelper.getUserId();
        SysUser sysUser = userMapper.selectById(userId);
        sysUser.setBalance(sysUser.getBalance().add(price));
        userMapper.updateById(sysUser);
        // 账单记录
        PUserBill bill = new PUserBill()
            .setCategory("1")
            .setUserId(userId)
            .setNumber(price)
            .setTitle(rechargeRequest.getTitle())
            .setType("1")
            .setPayType(rechargeRequest.getPayType())
            .setOrderNo(rechargeRequest.getOrderNo());
        baseMapper.insert(bill);
        // 上级佣金提取todo
    }

    @Override
    public WalletVO myWallet(String end, PageQuery pageQuery) {
        pageQuery.setPageNum((pageQuery.getPageNum() - 1) * pageQuery.getPageSize());
        WalletVO walletVO;
        walletVO = this.baseMapper.selectMyWallet(LoginHelper.getUserId());
        walletVO.setPUserBills(this.baseMapper.selectListCustom(pageQuery, end));
        return walletVO;
    }

    @Override
    public void insertTestFontByBo(POrderBo bo) {
        PUserBill bill = new PUserBill();
        bill.setOrderNo(bo.getOrderNo())
            .setUserId(LoginHelper.getUserId())
            .setCategory("2")
            .setType("1")
            .setPayType("0")
            .setTitle("余额充值")
            .setNumber(bo.getPrice());
        this.baseMapper.insert(bill);
    }
}
